/**
 * 处理动态表单数据
 * @example handleDynamicData('请求参数').then(res=>{ })
 */
import { list as listDesign } from "@/api/erp/voucherDesign";

import { IdFieldToNameField } from "@/utils/customize"

let _callbackData = [];  //返回的详细数据

async function handleDynamicData (code, isAreaPay, isAreaX) {
    let postData = {
        source: code,
    }
    await listDesign(postData).then((response) => {
        if (response.code === 200) {
            const { data } = response;

            //给动态表名新增value字段（用于提交数据）
            for (let i = 0; i < data.length; i++) {
                const element = data[i];
                //isAreaX新西亚项目 中 不是面积计算表 隐藏金额 和单价
                if (isAreaX && !isAreaPay) {
                    if (element.code == 'price' || element.code == 'amount') {
                        element.onOff = false;
                    }
                }
                if (element.columnType == '是否') {
                    element.value = false;
                } else {
                    element.value = '';
                    element.valueId = '';
                    element.valueName = '';
                }

            }
            _callbackData = filtrationData(data)
        } else {
            // this.$message.warning(res.message);
        }
    })
    return _callbackData;
}

function filtrationData (d) {
    d = d.filter(item => {
        return item.onOff == true;
    });

    return d;
}

function regroupTableColumns (data) {
    //重组表格columns
    const tableColumns = [];
    data.unshift({
        name: '序号',
        code: 'number',
        width: 50,
        fixed: 'left'
    })

    if (data && typeof data == 'object') {
        for (let i = 0; i < data.length; i++) {
            if (data[i].columnType == '搜索选择') {
                data[i].code = IdFieldToNameField(data[i].code)
            }
            let title = data[i].name;
            if (data[i].onFill) {
                title = <span>*</span> + data[i].name
            }
            let columns = {
                title: title,
                key: data[i].code,
                dataIndex: data[i].code,
                scopedSlots: { customRender: data[i].code },
                width: data[i].columnWidth,
                fixed: data[i].fixed,
                ellipsis: true,
            }
            tableColumns.push(columns)
        }
    } else {
        this.$message.error('dynamic-data:regroupTableColumns() error');
        return;
    }
    return tableColumns;
}

function regroupFromData (data) {
    //表单内容置空
    let m = [];
    for (const key in data) {
        m[data[key].code] = '';
    }
    return m;
}

/**
 * discountPrice:单价
 * taxPrice:含税单价
 * quantity:数量
 * taxRate：税率
 * discountAmount:金额
 * taxAmount:含税金额
*/
function calculate (calculateData) {

    // let discountPrice = calculateData.discountPrice;//单价
    // let quantity = calculateData.quantity;//数量
    // let taxPrice = calculateData.taxPrice;//含税单价
    // let taxRate = calculateData.taxRate;//税率
    // let discountAmount = null;//金额
    // let taxAmount = null;//含税金额
    // console.log(taxRate,discountPrice);

    // //含税单价=单价*（1+税率%）
    // if (taxRate && discountPrice) {
    //     alert(1);
    //     taxPrice = discountPrice * (1 + taxRate / 100);
    // } else {
    //     taxPrice = discountPrice * 1;
    // }

    // //单价=含税单价/（1+税率%）
    // if (taxRate && taxPrice) {
    //     alert(2)
    //     discountPrice = taxPrice * (1 + taxRate / 100);

    // } else {
    //     discountPrice = taxPrice * 1;
    // }

    // //金额=单价*数量
    // discountAmount = Number(discountPrice * quantity).toFixed(2);
    // //含税金额=含税单价*数量
    // taxAmount = Number(taxPrice * quantity).toFixed(2);

    // return {
    //     quantity: calculateData.quantity,//数量
    //     discountPrice: discountPrice,//单价
    //     taxPrice: taxPrice,//含税单价
    //     taxRate: taxRate,//单价
    //     discountAmount: discountAmount,//金额
    //     taxAmount: taxAmount,//含税金额
    // }
}


function regroupSubmitData (data) {
    //提交数据时 获取数据的value值
    let m = {};
    for (const key in data) {
        if (data[key].onEdit === true) {
            if (data[key].dataType == 1) {
                //系统字段
                if (data[key].valueId) {
                    //如果valueId存在，说明要提交的是选中的id
                    m[data[key].code] = data[key].valueId;
                } else {
                    m[data[key].code] = data[key].value;
                }
            } else {
                //自定义字段
                m[data[key].id] = data[key].value;
            }
        }
    }
    return m;
}
/**
 * 组装提交数据
 * data:{
 *  detail:明细
 *  header:表头
 *  footer:表尾
 *  customField：自定义字段
 *  /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/ 包含数字或者字母的code，就是自定义数据
 * }
 */
function submitRegData (data, defineData) {
    console.log(defineData);
    let commitData = {
        orderDetailList: [],//请购单明细
        defineFields: '',//自定义字段
    };

    let m = data.detail.slice(0, -1);//删除合计列

    let reg = /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/;//必须包含字母和数字
    console.log(data.detail);

    let s = [];//传给后台的明细表数据
    for (let i = 0; i < m.length; i++) {
        if (m[i].inventoryId || m[i].inventoryName) {//有物料id或者物料名字的才传给后台
            s.push(m[i])
        }
    }

    //明细表自定义数据
    for (const key in s) {
        let cust = {};
        for (const k in s[key]) {
            if (reg.test(k)) {

                let a = {};
                let itemid = '';

                for (let i = 0; i < defineData.length; i++) {
                    if (defineData[i].code == k) {
                        a[defineData[i].id] = s[key][k];
                    }
                }
                Object.assign(cust, a)
            }
        }
        s[key].defineFields = JSON.stringify(cust);
    }

    commitData.orderDetailList = Object.assign([], s);

    commitData.defineFields = JSON.stringify(regroupSubmitData(data.customField));

    return commitData = Object.assign(
        commitData,
        regroupSubmitData(data.header),
        regroupSubmitData(data.footer)
    )
}

export {
    handleDynamicData,
    regroupTableColumns,
    submitRegData,
    calculate
}

/**
 * 单据请求code汇总：
ArapReceiveVoucher	            收款单
ArapPaymentVoucher	            付款单
ArapStrikeBalanceAdvReceiveAr	预收冲应收
ArapStrikeBalanceAdvPaymentAp	预付冲应付
ArapStrikeBalanceArAr	        应收冲应收
ArapStrikeBalanceApAp	        应付冲应付
ArapStrikeBalanceArAp	        应收冲应付
ArapExchangeAdjust	汇兑损益调整单
bankCashAccessVoucher	银行存取款单
expenseVoucher	费用单
incomeVoucher	收入单
OtherPaymentVoucher	其他应付单
OtherReceiveCSVoucher	其他应收单
CashCheckVoucher	现金盘点单
GLDoc	凭证
OutSourceExpenseVoucher	委外费用单
OutSourceOrder	委外加工单

PurchaseRequisition	请购单
PurchaseOrder	采购订单
PuArrival	到货单
PurchaseInvoice	采购发票

PraVoucher	采购需求分析
PurchaseArrivalPeriodStart	期初进货单
SaleInvoice	销售发票
SaleOrder	销售订单
SaleQuotation	报价单
SaleDelivery	销售发货单
CostAllocationOrder	产品成本分配单
PurchaseReceiveVoucher	采购入库单
ProductReceiveVoucher	产成品入库单
OtherReceiveVoucher	其他入库单
AdjustCostInVoucher	入库调整单
SaleDispatchVoucher	销售出库单
MaterialDispatchVoucher	材料出库单
OtherDispatchVoucher	其他出库单
AdjustCostOutVoucher	出库调整单
StockRequestVoucher	领料单
TransVoucher	调拨单
CheckVoucher	盘点单
ShareExpenseVoucher	费用分摊单
PurchaseSettleVoucher	采购核算单
PSPurchaseReceiveVoucher	期初暂估入库单
PSSaleDispatchVoucher	期初销售出库单
RedBackVoucher	红字回冲单
BlueBackVoucher	蓝字回冲单
 */